package repostiory

import (
	"context"
	"gitee.com/chicken-c/go-learn/webook/internal/domain"
	"gitee.com/chicken-c/go-learn/webook/internal/repostiory/dao"
	"github.com/ecodeclub/ekit/sqlx"
)

var ErrSMSNotFound = dao.ErrSMSNotFound

type AsyncSmsRepository interface {
	Add(ctx context.Context, s domain.AsyncSms) error
	PreemptWaitingSMS(ctx context.Context) (domain.AsyncSms, error)
	ReportScheduleResult(ctx context.Context, id int64, success bool) error
}

type asyncSmsRepository struct {
	dao dao.AsyncSmsDAO
}

func (s *asyncSmsRepository) Add(ctx context.Context, as domain.AsyncSms) error {
	return s.dao.Insert(ctx, dao.AsyncSms{
		Config: sqlx.JsonColumn[dao.SmsConfig]{
			Val: dao.SmsConfig{
				TpiId: as.TqlId,
				Args:  as.Args,
			},
			Valid: true,
		},
		RetryMax: 3,
	})
}

func (s *asyncSmsRepository) PreemptWaitingSMS(ctx context.Context) (domain.AsyncSms, error) {
	ds, err := s.dao.GetWaitingSMS(ctx)
	if err != nil {
		return domain.AsyncSms{}, err
	}

	return domain.AsyncSms{
		Id:       ds.Id,
		TqlId:    ds.Config.Val.TpiId,
		Args:     ds.Config.Val.Args,
		Numbers:  ds.Config.Val.Numbers,
		RetryMax: ds.RetryMax,
	}, err
}

func (s *asyncSmsRepository) ReportScheduleResult(ctx context.Context, id int64, success bool) error {
	var err error
	if success {
		err = s.dao.MarkSuccess(ctx, id)
	} else {
		err = s.dao.MarkFailed(ctx, id)
	}

	return err
}
